package top.yinjinbiao.mqtt.client;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author yin.jinbiao
 * @Date 2021/9/22 9:17
 * @Version 1.0
 */
@Component
@Slf4j
public class MessageCallback implements MqttCallback {

    @Autowired
    private CustomMqttClient customMqttClient;

    /**
     * 丢失了对服务器端的连接后触发的回调
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        // 资源的清理、重连
        log.info("丢失了对服务器端的连接");
        customMqttClient.reConnect();
    }

    /**
     * 订阅者收到消息后触发的回调
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        log.info("订阅者订阅到了消息，topic={},messageid={},qos={},payload={}",
                topic,
                mqttMessage.getId(),
                mqttMessage.getQos(),
                new String(mqttMessage.getPayload()));
    }

    /**
     * 消息发布者发布消息完成产生的回调
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        int messageId = iMqttDeliveryToken.getMessageId();
        String[] topics = iMqttDeliveryToken.getTopics();
        log.info("消息发布完成, messageid={}, topics={}",messageId,topics);
    }
}
